<?php

namespace Beerus\Modules\DesignerCompetition2020\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Article;
use Doraemon\model\ArticleHouse;
use Doraemon\model\DesignerCompetition\Confirmation;
use Doraemon\model\DesignerCompetition\DesignerAwardSign2020;
use Doraemon\model\DesignerCompetition\FinalReview;
use Doraemon\model\DesignerCompetition\NavigatorScore;
use Doraemon\model\Member;
use Doraemon\service\DesignerCompetition2020\ReviewService;
use Doraemon\service\DesignerCompetition2020\SignService;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;

/**
 * 初筛确认
 *
 * @category   Module name
 * @package    PSR
 * @subpackage Documentation\API
 * @author     zhouyang  <zhouyang@haohaozhu.com>
 * @license    GPL http://www.haohaozhu.com
 * @link       http://www.haohaozhu.com
 */
class BeginVerifyController extends Controller
{
	const PAGE_SIZE = 10;

	public function __construct()
	{
		parent::__construct();
		Admin::script('$(".pjax-container").attr("id","pjax-container");');
	}

	/**
	 * 初筛确认
	 * @param Request $request
	 * @param Content $content
	 * @param int $tab_id
	 * @return Content
	 */
	public function index(Request $request, Content $content, $tab_id = 1)
	{
		$request_params = $request->all();

		$page_size = $request->input('per_page', self::PAGE_SIZE);
		$page = $request->input('page', 1);

		$condition = $this->condition($request_params, $tab_id);

		if ($tab_id == 1) {
			$condition['ORDER'] = ['house_score' => 'DESC'];
//            if (!empty($request_params['score_sort'])) {
//                $condition['ORDER'] = ['house_score' => $request_params['score_sort']];
//            }
		} elseif ($tab_id == 2) {
			$condition['ORDER'] = ['soft_score' => 'DESC'];
//            if (!empty($request_params['score_sort'])) {
//                $condition['ORDER'] = ['house_score' => $request_params['score_sort']];
//            }
		} elseif ($tab_id == 3) {
			$condition['ORDER'] = ['plane_score' => 'DESC'];
//            if (!empty($request_params['score_sort'])) {
//                $condition['ORDER'] = ['house_score' => $request_params['score_sort']];
//            }
		}

		$condition['LIMIT'] = [
			($page - 1) * $page_size,
			$page_size
		];

		$tab = new Tab();
		$tab->addLink('初筛确认（户型）', '/admin/DesignerCompetition2020/verify/first/1', $tab_id == 1);
		$tab->addLink('初筛确认（软装）', '/admin/DesignerCompetition2020/verify/first/2', $tab_id == 2);
		$tab->addLink('初筛确认（平面）', '/admin/DesignerCompetition2020/verify/first/3', $tab_id == 3);

		return $content
			->header('初筛确认')
			->breadcrumb(
				['text' => '初筛确认', 'url' => '/admin/DesignerCompetition2020/verify/first/' . $tab_id]
			)
			->body($tab)
			->row(self::indexGrid($condition, $tab_id));
	}

	private function condition($request, $tab)
	{
		$response = [
			'audit_status' => DesignerAwardSign2020::AUDIT_STATUS_CONFIRM,
			'channel' => DesignerAwardSign2020::FROM_DESIGNER
		];

		if ($tab == ReviewService::AWARD_PLANE) {
			$response['award_type'] = [
				DesignerAwardSign2020::DESIGNER_BEST_PLANE_AWARD,
				DesignerAwardSign2020::DESIGNER_BEST_PLANE_SOFT_AWARD];
		} elseif ($tab == ReviewService::AWARD_SOFT) {
			$response['award_type'] = [
				DesignerAwardSign2020::DESIGNER_BEST_SOFT_AWARD,
				DesignerAwardSign2020::DESIGNER_BEST_PLANE_SOFT_AWARD];
		}

		// 用户uid
		if (!empty($request['uid'])) {
			$response['uid'] = $request['uid'];
		}

		// 用户身份
		if (!empty($request['user_type'])) {
			$response['user_type'] = $request['user_type'];
		}

		// 赛区
		if (!empty($request['area'])) {
			$response['area'] = $request['area'];
		}

		// 户型
		if (!empty($request['house_model'])) {
			$response['house_model'] = $request['house_model'];
		}

		// 评审结果
		if (!empty($request['begin_audit']) && ($request['begin_audit'] !== 0)) {
			if ($tab == ReviewService::AWARD_HOUSE) {
				$response['house_audit'] = $request['begin_audit'];
			} elseif ($tab == ReviewService::AWARD_SOFT) {
				$response['soft_audit'] = $request['begin_audit'];
			} elseif ($tab == ReviewService::AWARD_PLANE) {
				$response['plane_audit'] = $request['begin_audit'];
			}
		}

		// 备注
		if (!empty($request['is_remark'])) {
			if ($request['is_remark'] == 1) {
				// 备注匹配
				if (isset($request['remark']) && ($request['remark'] !== '')) {
					$response['remark[~]'] = $request['remark'];
				} else {
					$response['remark[!]'] = '';
				}
			} elseif ($request['is_remark'] == 2) {
				// 备注匹配
				if (isset($request['remark']) && ($request['remark'] !== '')) {
					$response['id'] = 0;
				} else {
					$response['remark'] = '';
				}
			}
		}

		// 备注匹配
		if (isset($request['remark']) && ($request['remark'] !== '')) {
			$response['remark[~]'] = $request['remark'];
		}

		// 领航员总分
		if (!empty($request['score'])) {
			if ($tab == ReviewService::AWARD_HOUSE) {
				$response['house_score'] = explode(',', $request['score']);
			} elseif ($tab == ReviewService::AWARD_SOFT) {
				$response['soft_score'] = explode(',', $request['score']);
			} elseif ($tab == ReviewService::AWARD_PLANE) {
				$response['plane_score'] = explode(',', $request['score']);
			}
		}

		if (!empty($request['full_score'])) {
			$response['full_score[>=]'] = 1;
		}

		return $response;
	}

	/**
	 * 表格展示部分
	 * @param $condition
	 * @param $tab_id
	 * @return Grid
	 */
	public function indexGrid($condition, $tab_id)
	{
		Admin::script($this->jumpScript());

		$lists = DesignerAwardSign2020::select('*', $condition);

		unset($condition['ORDER']);
		unset($condition['LIMIT']);
		$total = DesignerAwardSign2020::count('*', $condition);

		if (!empty($lists)) {
			$user_ids = array_column($lists, 'uid');
			$member_info = Member::getUsers($user_ids);
			$confirm_data = DesignerAwardSign2020::listByCondition([
				'AND' => [
					'uid' => $user_ids,
				],
				'OR' => [
					'house_audit' => 1,
					'plane_audit' => 1,
					'soft_audit' => 1
				]
			]);

			$map_confirm = [];
			foreach ($confirm_data as $confirm) {
				if (empty($map_confirm[$confirm['uid']]) && $map_confirm[$confirm['uid']] != 0) {
					$map_confirm[$confirm['uid']] = 0;
				} else {
					$map_confirm[$confirm['uid']]++;
				}
			}

			foreach ($lists as &$item) {
				// 用户信息
				$item['nick'] = empty($member_info[$item['uid']]['nick']) ? '' : $member_info[$item['uid']]['nick'];
				$item['user_type'] = SignService::USER_TYPE[$member_info[$item['uid']]['type']];

				// 参赛信息
				$item['from_name'] = SignService::FROM[$item['channel']];
				$item['area_text'] = SignService::AREA[$item['area']];
				$item['house_model'] = SignService::HOUSE_MODEL[$item['house_model']];
				$item['confirm_num'] = empty($map_confirm[$item['uid']]) ?
					0 : "<b style='color: red'>" . $map_confirm[$item['uid']] . "</b>";

				$item['is_plane'] = $item['is_soft'] = '否';
				if ($item['award_type'] == DesignerAwardSign2020::DESIGNER_BEST_PLANE_AWARD) {
					$item['is_plane'] = '是';
				} elseif ($item['award_type'] == DesignerAwardSign2020::DESIGNER_BEST_SOFT_AWARD) {
					$item['is_soft'] = '是';
				} elseif ($item['award_type'] == DesignerAwardSign2020::DESIGNER_BEST_PLANE_SOFT_AWARD) {
					$item['is_plane'] = $item['is_soft'] = '是';
				}

				$item['sign_time'] = date('Y-m-d H:i:s', $item['add_time']);

				// 作品链接
				if ($item['channel'] == DesignerAwardSign2020::FROM_OWNER) {
					$article_info = Article::getArticle($item['article_id']);
					$item['work_name'] = empty($article_info) ? '作品名称无' : $article_info['title'];
					$item['link'] = Hhzurl::getDomain() . "/bangyang/{$item['article_id']}.html";
					$item['work_pic_url'] = ImgUrl::getUrl(
						ImgUrl::APPTYPE_APP,
						$article_info['cover_pic_id'],
						ImgUrl::IMAGE_SIZE_SQ_PHONE
					);
					// 初筛分数
					$item['score'] = '';
				} elseif ($item['channel'] == DesignerAwardSign2020::FROM_DESIGNER) {
					$live_photos = json_decode($item['live_photos'], true);
					$item['live_photos'] = $live_photos;
					$work_pic_url = ImgUrl::getUrl(
						ImgUrl::APPTYPE_APP,
						$live_photos[0]['pic_id'],
						ImgUrl::IMAGE_SIZE_SQ_PHONE
					);
					$item['work_pic_url'] = $work_pic_url; // 取实景作品的第一条

					$item['link'] = Hhzurl::getDomain() . "/designer/game/2020/production-detail?id={$item['id']}";

					// 获取当前参赛作品所在赛区的领航员
					$navigators = ReviewService::REVIEWER[$item['area']];
					// 查询用户nick
					$navigators_info = Member::getUsers($navigators);

					$score_info = [];
					foreach ($navigators as $navigator) {
						$nick = empty($navigators_info[$navigator]['nick']) ?
							'未知用户' : $navigators_info[$navigator]['nick'];
						$condition = [
							'sign_id' => $item['id'],
							'uid' => $navigator,
						];
						$review_record = NavigatorScore::getByCondition($condition);

						if (empty($review_record)) {
							$score_info[] = "{$nick}：未打分";
						} else {
							if ($tab_id == ReviewService::AWARD_HOUSE) {
								if (empty($review_record['house_score'])) {
									$score_info[] = "{$nick}：未打分";
								} else {
									$score = (int)$review_record['house_score'];

									if ($score == 3) {
										$score_info[] = "{$nick}：<b style='color: red'>{$score}分</b>";
									} else {
										$score_info[] = "{$nick}：{$score}分";
									}
								}
							} elseif ($tab_id == ReviewService::AWARD_PLANE) {
								if (empty($review_record['plane_score'])) {
									$score_info[] = "{$nick}：未打分";
								} else {
									$score = (int)$review_record['plane_score'];

									if ($score == 3) {
										$score_info[] = "{$nick}：<b style='color: red'>{$score}分</b>";
									} else {
										$score_info[] = "{$nick}：{$score}分";
									}
								}
							} elseif ($tab_id == ReviewService::AWARD_SOFT) {
								if (empty($review_record['soft_score'])) {
									$score_info[] = "{$nick}：未打分";
								} else {
									$score = (int)$review_record['soft_score'];

									if ($score == 3) {
										$score_info[] = "{$nick}：<b style='color: red'>{$score}分</b>";
									} else {
										$score_info[] = "{$nick}：{$score}分";
									}
								}
							}
						}
					}

					$total_score = 0;
					if ($tab_id == ReviewService::AWARD_HOUSE) {
						$total_score = $item['house_score'];
						$item['begin_audit'] = $item['house_audit'];
					} elseif ($tab_id == ReviewService::AWARD_PLANE) {
						$total_score = $item['plane_score'];
						$item['begin_audit'] = $item['plane_audit'];
					} elseif ($tab_id == ReviewService::AWARD_SOFT) {
						$total_score = $item['soft_score'];
						$item['begin_audit'] = $item['soft_audit'];
					}

					$score_info[] = "<b style='color: blue'>总分：" . $total_score . "分</b>";
					$item['score_info'] = implode('<br/>', $score_info);
				}

				// 作品信息
				$article_house = ArticleHouse::getArticleHouseById($item['article_id']);

				$item['house_construction'] = $item['house_stuff'] = $item['house_area'] = '';
				if (!empty($article_house)) {
					// 户型
					$house_arr = explode(',', $article_house['house_construction']);
					$item['house_construction'] = $house_arr[0] . '室';
					$item['house_area'] = $article_house['area_name'];
				}

				// 常住人口
				if ($item['people'] == 5) {
					$people = $item['other_people'];
				} else {
					$people = DesignerAwardSign2020::PEOPLE[$item['people']];
				}
				$item['people'] = $people;
			}
			unset($item);
		}

		$gridModel = new pGridDataModel($lists, $total, [
			'perPage' => self::PAGE_SIZE
		]);

		$gridList = Admin::grid(
			$gridModel,
			function (Grid $grid) use ($gridModel) {
				$grid->paginate($gridModel->getPerPage());
				$grid->disableCreateButton();
				$grid->disableExport();
				$grid->disableRowSelector();

				$grid->filter(function (Grid\Filter $filter) {
					$filter->disableIdFilter();

					$filter->column(1 / 2, function ($filter) {
						// 用户身份
						$filter->equal('user_type', '用户身份')->select(SignService::USER_TYPE_MAP);
						// 赛区
						$filter->equal('area', '赛区')->select(SignService::AREA);
						// 户型
						$filter->equal('house_model', '户型')->select(SignService::HOUSE_MODEL);
						// 评审结果
						$filter->equal('begin_audit', '评审结果')->select(ReviewService::AUDIT_STATUS_MAP);
						// 至少获得一个满分作品
						$filter->equal('full_score', '至少获得一个满分')->checkbox([
							0 => ''
						]);
					});

					$filter->column(1 / 2, function ($filter) {
						$options = ['-1' => '全部', '1' => '是', '2' => '否'];
						// 包含备注
						$filter->equal('is_remark', '包含备注')->radio($options)->default('-1');
						// 备注内容
						$filter->equal('remark', '备注内容');
						// 用户uid
						$filter->equal('uid', '用户uid');
						// 领航员总分
						$filter->equal('score', '领航员总分');
					});

					$filter->expand();
				});

				$grid->column('id', '报名id')->width(70);
				$grid->column('user_info', '用户信息')->width(140)->display(function () {
					$userInfo[] = 'uid：' . $this->uid;
					$userInfo[] = '昵称：<a class="jump_user" href="javascript:void(0);"> ' . $this->nick . '</a>';
					$userInfo[] = '身份：' . $this->user_type;
					return implode('<br/>', $userInfo);
				});

				$grid->column('competition_info', '参赛信息')->width(240)->display(function () {
					if ($this->channel == DesignerAwardSign2020::FROM_OWNER) {
						$competition_info[] = '通道：' . $this->from_name;
						$competition_info[] = '报名时间：' . $this->sign_time;

						return implode('<br/>', $competition_info);
					} elseif ($this->channel == DesignerAwardSign2020::FROM_DESIGNER) {
						$competition_info[] = '通道：' . $this->from_name;
						$competition_info[] = '赛区：' . $this->area_text;
						$competition_info[] = '户型：' . $this->house_model;
						$competition_info[] = '软装：' . $this->is_soft;
						$competition_info[] = '平面：' . $this->is_plane;
						$competition_info[] = '报名时间：' . $this->sign_time;
						$competition_info[] = '已入围作品数：' . $this->confirm_num;

						return implode('<br/>', $competition_info);
					} else {
						return '报名入口来源未知';
					}
				});

				$grid->column('work_link', '作品链接')->width(210)->display(function () {
					$open = isset($this->work_name) ? '<a class="fa " href="javascript:layer.open({type: 2, 
                    title: \'预览\', maxmin: true, area: [\'650px\', \'700px\'], 
                    content: \'' . $this->link . '\' });">' . htmlentities($this->work_name) . '</a>' : "";
					$img = "<img width='200' height='200' src='{$this->work_pic_url}'>";
					return implode('<br/>', [$img, $open]);
				});

				$grid->column('work_info', '作品信息')->width(400)->display(function () {
					$work_info = [];
					if ($this->channel == DesignerAwardSign2020::FROM_OWNER) {
						return '无';
					} elseif ($this->channel == DesignerAwardSign2020::FROM_DESIGNER) {
						$work_info[] = '户型：' . $this->house_construction;
						$work_info[] = '总造价：' . $this->total_price . '万元';
						$work_info[] = '地区：' . $this->house_area;
						$work_info[] = '常住人口：' . $this->people;
						$work_info[] = '项目完成时间：' . $this->design_finish_date;
						$work_info[] = '满意的产品：' . $this->most_satisfied;
						$work_info[] = '产品品牌：' . $this->satisfied_brand;
						$work_info[] = '满意的原因：' . $this->satisfied_reason;

						return implode('<br/>', $work_info);
					} else {
						return '报名入口来源未知';
					}
				});

				$grid->column('score_info', '初筛分数')->width(240)->display(function () {
					if ($this->channel == DesignerAwardSign2020::FROM_OWNER) {
						return $this->score_info;
					} elseif ($this->channel == DesignerAwardSign2020::FROM_DESIGNER) {
						return $this->score_info;
					} else {
						return '报名入口来源未知';
					}
				});

				$grid->column('begin_audit', '评审结果')->width(100)->radio(ReviewService::AUDIT_STATUS_MAP);

				$grid->column('remark', '备注')->width(200)->editable();

				$grid->actions(function (Grid\Displayers\Actions $actions) {
					$actions->disableDelete();
				});
				$grid->disableActions();
			}
		);

		return $gridList;
	}

	private function jumpScript()
	{
		return <<<SCRIPT
        // 用户详情跳转
        $('.jump_user').unbind('click').click(function(){
            let win = window.open('http://manage.haohaozhu.me/','用户详情','name=用户详情');
            win.openapp('/User/Oauthadmin/detail/uid/608209','user_detail608209','用户详情');
        });
        
        $('.btn-xs').hide();
        
        $("input[name='grid-radio-begin_audit']").change(
		function() {
		        id = $(this).parents('.grid-radio-begin_audit')[0].getAttribute('data-key');
                var begin_audit = $(this).val();
                
                var tab = 1;
                if (window.location.href.indexOf("?") != -1) {
                    tab = window.location.href.split('?')[0].split('/').pop();
                } else {
                    tab = window.location.href.split('/').pop();
                }
                
                $.ajax({
                    url: '/admin/DesignerCompetition2020/verify/first/audit/' + id,
                    type: "POST",
                    data: {_method:"PUT", begin_audit: begin_audit, tab_id: tab},
                    dataType:"json",
                    success:function(result){
                        if (result.status) {
                            toastr.success(result.message);
                        } else {
                            toastr.warning(result.message);
                        }
                    },
                    error:function(){
                        toastr.error('系统错误,请联系管理员');
                    }
                });
	    });
SCRIPT;
	}

	public function review(Request $request, $id)
	{
		$pjax = true;
		$status = true;
		$begin_audit = $request->input('begin_audit');
		$award_type = $request->input('tab_id');

		$message = "修改成功";
		try {
			$sign_info = DesignerAwardSign2020::getById($id);

			if (isset($begin_audit)) {
				if ($award_type == ReviewService::AWARD_HOUSE) {
					DesignerAwardSign2020::update(['house_audit' => $begin_audit], ['id' => $id]);
				} elseif ($award_type == ReviewService::AWARD_SOFT) {
					DesignerAwardSign2020::update(['soft_audit' => $begin_audit], ['id' => $id]);
				} elseif ($award_type == ReviewService::AWARD_PLANE) {
					DesignerAwardSign2020::update(['plane_audit' => $begin_audit], ['id' => $id]);
				}

				$condition = [
					'sign_id' => $id,
					'award_type' => $award_type,
					'stage' => Confirmation::STAGE_FIRST
				];
				$result = Confirmation::getByCondition($condition);

				$user_info = Member::getUser($sign_info['uid']);

				$data = [
					'area' => $sign_info['area'],
					'house_model' => $sign_info['house_model'],
					'award_type' => $award_type,
					'audit_status' => $begin_audit,
					'admin_id' => Admin::user()->id,
					'stage' => Confirmation::STAGE_FIRST,
					'nick' => empty($user_info['nick']) ? '' : $user_info['nick'],
					'article_id' => $sign_info['article_id'],
				];

				if (empty($result)) {
					// 记录初筛确认结果
					$data['sign_id'] = $id;
					$data['add_time'] = time();

					Confirmation::create($data);
				} else {
					$data['edit_time'] = time();
					Confirmation::update($data, $condition);

					if ($begin_audit == Confirmation::AUDIT_STATUS_NO) {
						Confirmation::delete($condition);
						FinalReview::delete([
							'sign_id' => $id,
							'award_type' => $award_type,
						]);
					}
				}

				if ($begin_audit == Confirmation::AUDIT_STATUS_PASS) {
					$judge = ReviewService::JUDGE[$sign_info['area']];

					$data = [];
					foreach ($judge as $uid) {
						$data[] = [
							'sign_id' => $id,
							'area' => $sign_info['area'],
							'house_model' => $sign_info['house_model'],
							'uid' => $uid,
							'award_type' => $award_type,
							'add_time' => time()
						];
					}
					FinalReview::create($data);
				}
			} else {
				throw new \Exception('缺少参数错误');
			}
		} catch (\Exception $e) {
			$status = false;
			$message = $e->getMessage();

			if (!$pjax) {
				return response()->json(['errors' => [$message]], 422);
			}
		}

		return response()->json(compact('message', 'status'));
	}

	public function remark(Request $request, $tab, $id)
	{
		$pjax = true;
		$status = true;
		$name = $request->input('name');
		$value = $request->input('value');

		$message = "修改成功";
		try {
			if (isset($name) && isset($value)) {
				switch ($name) {
					case 'remark':
						$pjax = false;
						if (mb_strlen($value) > 300) {
							throw new \Exception('最多300字');
						}
						DesignerAwardSign2020::update(['remark' => $value], ['id' => $id]);
						$result = Confirmation::getByCondition([
							'award_type' => $tab,
							'sign_id' => $id
						]);
						$sign_info = DesignerAwardSign2020::getById($id);

						if (empty($result)) {
							Confirmation::create([
								'stage' => Confirmation::STAGE_FIRST,
								'sign_id' => $id,
								'area' => $sign_info['area'],
								'house_model' => $sign_info['house_model'],
								'award_type' => $tab,
								'remark' => $value,
								'add_time' => time(),
								'admin_id' => Admin::user()->id
							]);
						} else {
							Confirmation::update([
								'remark' => $value,
								'edit_time' => time(),
								'admin_id' => Admin::user()->id
							], [
								'sign_id' => $id,
								'award_type' => $tab,
								'stage' => Confirmation::STAGE_FIRST
							]);
						}
						break;
					default:
						throw new \Exception('未开发功能');
						break;
				}
			}
		} catch (\Exception $e) {
			$status = false;
			$message = $e->getMessage();

			if (!$pjax) {
				return response()->json(['errors' => [$message]], 422);
			}
		}

		return response()->json(compact('message', 'status'));
	}
}
